package com.ms.utiles;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ms.exception.BusinessException;
import com.ms.properties.OssProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@Component
@Slf4j
@RequiredArgsConstructor
public class OssUtil {

    private final OssProperties ossProperties;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 上传文件到OSS
     * @param file 文件对象
     * @param fileType 文件类型 (audio/image)
     * @return OSS文件路径
     */
    public String uploadFile(MultipartFile file, String fileType) {
        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);

        if (!isValidExtension(fileExtension, fileType)) {
            throw new BusinessException("不支持的文件类型: " + fileExtension);
        }

        // 生成唯一文件名
        String fileName = generateFileName(fileType, fileExtension);

        try {
            // 上传文件
            ossClient.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + fileName;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 删除OSS文件
     * @param fileUrl 文件URL
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isBlank(fileUrl)) return;

        try {
            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            ossClient.deleteObject(ossProperties.getBucketName(), fileName);
        } catch (Exception e) {
            log.warn("删除OSS文件失败: {}", fileUrl, e);
        }
    }

    private String generateFileName(String fileType, String extension) {
        String prefix = "";
        if ("audio".equals(fileType)) {
            prefix = "audio/";
        } else if ("image".equals(fileType)) {
            prefix = "image/";
        }
        return prefix + UUID.randomUUID() + "." + extension;
    }

    private boolean isValidExtension(String extension, String fileType) {
        if ("audio".equals(fileType)) {
            return Arrays.asList("mp3", "wav", "flac", "m4a").contains(extension.toLowerCase());
        } else if ("image".equals(fileType)) {
            return Arrays.asList("jpg", "jpeg", "png", "gif", "webp").contains(extension.toLowerCase());
        }
        return false;
    }

    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }
}
